﻿using System;
using System.Collections.Generic;
using System.Text;

namespace Common
{
    public class ToolsReflect
    {
        public static object GetValue<T>(T obj, string propertyName)
        {
            Type type = obj.GetType();
            System.Reflection.PropertyInfo propertyInfo = type.GetProperty(propertyName);
            if (propertyInfo != null)
                return propertyInfo.GetValue(obj, null);
            else
                return null;
        }

        public static string GetValueToString<T>(T obj, string propertyName)
        {
            Type type = obj.GetType();
            System.Reflection.PropertyInfo propertyInfo = type.GetProperty(propertyName);
            if (propertyInfo != null)
            {
                Object o = propertyInfo.GetValue(obj, null);
                if (o == null)
                    return null;
                else
                    return o.ToString();
            }
            else
                return null;
        }

        public static void SetValue<T>(T obj, string propertyName, object propertyValue)
        {
            Type type = obj.GetType();//获取类型
            System.Reflection.PropertyInfo propertyInfo = type.GetProperty(propertyName);
            if (propertyInfo != null)
                propertyInfo.SetValue(obj, propertyValue, null);
        }
    }
}
